package dht.socket;

import java.io.IOException;
import java.net.Socket;
import java.util.Queue;

import dht.entity.NodeInfo;
import dht.throwable.DhtException;

public class TcpConnection {

	protected NodeInfo localInfo;
	protected SocketListener serverSocket;
	protected Queue<SocketHandler> socketQueue;

	public TcpConnection(NodeInfo localInfo, Queue<SocketHandler> socketQueue) {
		this.localInfo = localInfo;
		this.socketQueue = socketQueue;
	}

	public void runServerSocket(int port) throws DhtException {
		serverSocket = new SocketListener(port, localInfo, socketQueue);
		new Thread(serverSocket).start();
	}

	public SocketHandler genTransactionSocketHandler(NodeInfo serverInfo)
			throws DhtException {
		Socket socket = null;
		try {
			socket = new Socket(serverInfo.getIp(), serverInfo.getPort());
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		SocketHandler socketHandler = new SocketHandler(localInfo, socket);
		return socketHandler;
	}
}
